var sha1 = require('sha1');
var http = require ('http');
var url = require('url');
var util = require('util');
var querystring = require('querystring');
var xml2js = require('xml2js');

var config = {
    token: 'pengloo53',
    appid: 'wx27ebfbeddddaea30',
};

http.createServer(function(req,res){
    var method = req.method;
    switch (method){
        case 'GET':
            if(valide(req,res)){
                replayContext(req,res);
            }
            break;
        case 'POST':
            console.log('hi1');
            getDataFromXML(req,res);

    }
}).listen(9090);

console.log('Weixin Server is Started at port 9090');


/***
    被动回复文本消息
    <xml>
        <ToUserName><![CDATA[toUser]]></ToUserName>
        <FromUserName><![CDATA[fromUser]]></FromUserName>
        <CreateTime>12345678</CreateTime>
        <MsgType><![CDATA[text]]></MsgType>
        <Content><![CDATA[你好]]></Content>
    </xml>
*/
function replayContext(req,res){
    var context = '<xml>' + 
        '<ToUserName><![CDATA[toUser]]></ToUserName>' + 
        '<FromUserName><![CDATA[fromUser]]></FromUserName>' +
        '<CreateTime>12345678</CreateTime>' +
        '<MsgType><![CDATA[text]]></MsgType>' +
        '<Content><![CDATA[你好]]></Content>' +
        '</xml>';

}

/**
    处理XML数据
*/
function getDataFromXML(req,res){
    var bufferHelper = new BufferHelper();
    var _this = this;
    _this.res = res;
    req.setEncoding('utf-8');
    req.on('data', function (chunk) {
        bufferHelper.concat(chunk);
    });
    req.on('end', function () {
        xml2js.parseString(bufferHelper.toBuffer().toString(), function (err, json) {
            if (err) {
                _this.err = err;
            } else {
                _this.msg = _this.parseJson(json.xml);
                console.log(_this.msg);
            }
        });
    });
}

/**
    解析XML成JSON
*/
function toJSON(xml){
    var message = {};
    xml2js.parseString(xml, function(err,result){
        var data = result.xml;
        message.ToUserName = data.ToUserName[0];
        message.FromUserName = data.FromUserName[0];
        message.CreateTime = data.CreateTime[0];
        message.MsgType = data.MsgType[0];
        message.Content = data.Content[0];
        return message;
    });
}

/***
    test xml2js
*/
function test_xml(){
    var xml_data = '<xml><username>Lupeng</username><password>123456</password></xml>';
    xml2js.parseString(xml_data,function(err,results){
        console.log(results.xml.username[0]);
    });
}

/***
    微信认证
*/
function valide(req,res){
    var query = url.parse(req.url,true).query;
    var signature = query.signature;
    var timestamp = query.timestamp;
    var nonce = query.nonce;
    var echostr = query.echostr;
    var token = 'pengloo53';
    var array = new Array (token,timestamp,nonce);
    array.sort();
    var arraystring = array.join('');
    arraystring = sha1(arraystring);
    if (arraystring == signature){
        console.log("验证成功！");
        res.writeHeader(200,{"Content-Type":"text/html"});
        res.end(echostr);
        return true; 
    }else{
        return false;
    }
}